#include "./hash-table.h"
#include <iostream>

int getHash(int key)
{
	return key % m;
}

void initHashTable(HashTable &table)
{
	table.elem = (int *)malloc(TABLE_SIZE * sizeof(int));
	table.count = 0;
	for (int i = 0; i < TABLE_SIZE; i++)
	{
		table.elem[i] = NULL_KEY;
	}
}

void putTable(HashTable &table, int key)
{
	int addr = getHash(key);
	// 使用开放定址法的线性探测解决冲突问题
	while (table.elem[addr] != NULL_KEY)
	{
		addr = (addr + 1) % m;
	}
	table.elem[addr] = key;
}

int getTable(HashTable &table, int key)
{
	int addr = getHash(key);
	// 若找到的键和要找的键不一样
	while (table.elem[addr] != key)
	{
		addr = (addr + 1) % m;
		// 若使用开放定址法找到的是空或者循环回到原点则说明这个键不存在
		if (table.elem[addr] == NULL_KEY || addr == getHash(key))
		{
			return -1;
		}
	}
	return addr;
}